﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity;
using Eqwww.Domain.Models.Identity;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Eqwww.Data;
using System.Linq;
using Eqwww.Code;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Eqwww.Domain;

namespace Eqwww.App.Identity
{
    public class RoleApp : RoleManager<RoleModel>
    {
        private IModelHandler _modelHandler;
        private ApplicationDbContext _context;

        public RoleApp(IRoleStore<RoleModel> roleStore,
            IEnumerable<IRoleValidator<RoleModel>> roleValidators,
            ILookupNormalizer lookupNormalizer,
            IdentityErrorDescriber identityErrorDescriber,
            ILogger<RoleManager<RoleModel>> logger,
            IModelHandler modelHandler,
            ApplicationDbContext context)
            :base(roleStore, roleValidators, lookupNormalizer, identityErrorDescriber, logger)
        {
            _modelHandler = modelHandler;
            _context = context;
        }

        public async Task<ModelResult> AppCreateAsync(RoleModel model)
        {
            var exist = Roles.AsNoTracking().Any(x => x.Name.ToUpper() == model.Name.ToUpper());
            if (exist)
                return Common.ErrorResult("编码重复");
            _modelHandler.Create(model);
            var result = await CreateAsync(model);
            if (result.Succeeded)
            {
                await _context.SaveChangesAsync();
                return Common.SuccessResult();
            }
            else
            {
                var sb = new StringBuilder();
                foreach(var error in result.Errors)
                {
                    sb.Append("<br/>" + error.Code + ":" + error.Description);
                }
                return Common.ErrorResult(sb.ToString());
            }

            
        }

        public async Task<ModelResult> AppUpdateAsync(RoleModel model)
        {
            var oldModel = await FindByIdAsync(model.Id);
            if (oldModel == null)
                return Common.ErrorResult("指定角色不存在");
            if (oldModel.IsSystem == true)
                return Common.ErrorResult("系统角色不允许修改");
            var exist = await Roles.AnyAsync(x => x.Name.ToUpper() == model.Name.ToUpper() && x.Id != model.Id);
            if (exist)
                return Common.ErrorResult("编码重复");

            oldModel.Name = model.Name;
            oldModel.ShowName = model.ShowName;
            oldModel.SortCode = model.SortCode;
            oldModel.Description = model.Description;
           
            _modelHandler.Update(oldModel);
            var result = await UpdateAsync(oldModel);
            if (result.Succeeded)
            {
                
                await _context.SaveChangesAsync();
                return Common.SuccessResult();
            }
            else
            {
                var sb = new StringBuilder();
                foreach (var error in result.Errors)
                {
                    sb.Append("<br/>" + error.Code + ":" + error.Description);
                }
                return Common.ErrorResult(sb.ToString());
            }
        }

        public async Task<ModelResult> AppRemoveAsync(string id)
        {
            var model = Roles.FirstOrDefault(x => x.Id == id);
            if (model == null)
                return Common.ErrorResult("指定id的角色不存在");
            if (model.IsSystem == true)
                return Common.ErrorResult("系统角色不允许移除");

            

            _modelHandler.Delete(model);
            var result = await UpdateAsync(model);
            if (result.Succeeded)
            {
                await _context.SaveChangesAsync();
                return Common.SuccessResult();
            }
            else
            {
                var sb = new StringBuilder();
                foreach (var error in result.Errors)
                {
                    sb.Append("<br/>" + error.Code + ":" + error.Description);
                }
                return Common.ErrorResult(sb.ToString());
            }
        }

        /// <summary>
        /// 获取角色列表分页数据
        /// </summary>
        /// <param name="pagination"></param>
        /// <returns></returns>
        public IEnumerable<RoleModel> GetPagedIQueryable(Pagination pagination)
        {
            var exp = ExtLinq.True<RoleModel>();
            exp = exp.And(x => x.DeleteMark != true);
            var data = _context.FindQueryable(exp, pagination).Include(x=>x.CreateUser);
            return data;
        }

        public ModelResult UpdateIsSystem(string id, bool issystem)
        {
            var model = FindByIdAsync(id).Result;
            if (model == null)
                return Common.ErrorResult("未找到指定id的实体");

            model.IsSystem = issystem;
            var result = UpdateAsync(model).Result;
            return Common.SuccessResult();
        }


    }
}
